import { DataTypes, Model, Optional } from 'sequelize';
import sequelize from '../db';

interface SystemConfigAttributes {
  id: string;
  tenantId?: string;
  configKey: string;
  configValue?: string;
  configType: 'string' | 'number' | 'boolean' | 'json';
  description?: string;
  isSystem: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface SystemConfigCreationAttributes
  extends Optional<SystemConfigAttributes, 'id' | 'tenantId' | 'configValue' | 'description' | 'isSystem'> {}

class SystemConfig
  extends Model<SystemConfigAttributes, SystemConfigCreationAttributes>
  implements SystemConfigAttributes
{
  public id!: string;
  public tenantId?: string;
  public configKey!: string;
  public configValue?: string;
  public configType!: 'string' | 'number' | 'boolean' | 'json';
  public description?: string;
  public isSystem!: boolean;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

SystemConfig.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'tenant_id',
    },
    configKey: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'config_key',
    },
    configValue: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'config_value',
    },
    configType: {
      type: DataTypes.STRING(50),
      allowNull: false,
      defaultValue: 'string',
      field: 'config_type',
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true,
    },
    isSystem: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      field: 'is_system',
    },
  },
  {
    sequelize,
    tableName: 'system_configs',
    underscored: true,
    timestamps: true,
  }
);

export default SystemConfig;

